<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="goodsQueryRef"
      :inline="true"
      class="globalSerchFormStyle"
      label-width="80px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="commodityName">
            <el-input
              v-model="queryParams.commodityName"
              placeholder="请输入商品名称"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品编码" prop="commodityCode">
            <el-input
              v-model="queryParams.commodityCode"
              placeholder="请输入商品编码"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属分类" prop="categoryId">
            <el-cascader
              v-model="queryCategoryIds"
              :options="categoryOptions"
              :props="{
                checkStrictly: true,
                label: 'categoryName',
                value: 'categoryId',
                children: 'children',
              }"
              filterable
              clearable
              size="small"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="dateRange">
            <el-date-picker
              v-model="datetimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
              style="width: 190px"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" plain @click="resetQuery">
          重置
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          size="mini"
          plain
          @click="handleGoods('add', {})"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-delete"
          size="mini"
          plain
          :disabled="selectionList.length <= 0"
          @click="deleteDialogVisible = true"
        >
          批量删除
        </el-button>
      </el-col>
    </el-row>

    <!-- table -->
    <el-table
      :data="goodListTable"
      style="width: 100%"
      @selection-change="handleSelectChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="50" align="left">
      </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="left">
      </el-table-column>
      <el-table-column
        prop="commodityName"
        label="商品名称"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="commodityCode"
        label="商品编码"
        width="130"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="所属分类"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="retailPrice"
        label="零售价格(元)"
        width="120"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="salePrice"
        label="销售价格(元)"
        width="120"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="inventory"
        label="库存"
        width="120"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleGoods('detail', scope.row)"
            >查看</el-button
          >
          <el-button type="text" @click="handleGoods('edit', scope.row)"
            >编辑</el-button
          >
          <el-button type="text" @click="handlePutway(scope.row)"
            >上架</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      :hidden="total > 0 ? false : true"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :autoScroll="true"
    />

    <!-- 新增，编辑，查看商品分类抽屉 -->
    <GoodForm
      @reloadData="getList"
      :currentGoodInfo="currentGoodInfo"
      :action="action"
      :goodFormDialogVisiable.sync="goodFormDialogVisiable"
    ></GoodForm>

    <!-- 批量删除弹框 -->
    <el-dialog title="删除商品" :visible.sync="deleteDialogVisible" width="30%">
      <span>确定删除所选商品？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 商品上架 -->
    <GoodPutway
      :putwayDialog.sync="putwayDialog"
      :currentGoodInfo="currentGoodInfo"
      @reloadData="getList"
    ></GoodPutway>
  </div>
</template>
<script>
import {
  getCommodityListApi,
  pathDeleteCommodityApi,
} from "@/api/nonOil/goods";
import { getNonOilCategoryTreeApi } from "@/api/nonOil/class";
import Treeselect from "@riophae/vue-treeselect";
import GoodForm from "./good_form.vue";
import GoodPutway from "./good_putway.vue";
import { cloneDeep } from "lodash";
export default {
  name: "GoodList",
  components: { Treeselect, GoodForm, GoodPutway },
  data() {
    return {
      total: 0,
      loading: false,
      queryCategoryIds: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      datetimeRange: [], // 搜索条件的时间范围
      goodListTable: [],
      categoryOptions: [], // 所属分类列表
      goodFormDialogVisiable: false,
      currentGoodInfo: {}, // 当前商品信息
      action: "",
      selectionList: [],
      deleteDialogVisible: false, // 删除弹框
      putwayDialog: false, // 上架弹框
    };
  },
  mounted() {
    this.getList();
    this.getNonOilCategoryList();
  },
  methods: {
    // 获取商品列表
    async getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.datetimeRange && this.datetimeRange.length) {
        params.beginTime = this.datetimeRange[0];
        params.endTime = this.datetimeRange[1];
      }
      // 处理搜索条件中的分类id
      if (this.queryCategoryIds.length) {
        let ids = this.queryCategoryIds;
        params.categoryId = ids[ids.length - 1];
      }
      const res = await getCommodityListApi(params);
      this.loading = false;
      this.goodListTable = res.rows;
      this.total = res.total;
    },

    // 处理搜索条件中的所属分类数据
    handleCategoryOption(list) {
      const temlist = []; // 存放处理后的结果
      list.forEach((item) => {
        const obj = {};
        obj.categoryId = item.categoryId;
        obj.categoryName = item.categoryName;
        obj.value = item.categoryId;
        obj.label = item.categoryName;
        if (item.children && item.children.length > 0) {
          obj.children = this.handleCategoryOption(item.children); // 如果有children，则继续递归调用
        } else {
          obj.children = null; // children为空
        }
        temlist.push(obj);
      });
      return temlist;
    },

    // 获取分类列表
    async getNonOilCategoryList() {
      const res = await getNonOilCategoryTreeApi();
      this.categoryOptions = res.data.children;
      // this.categoryOptions = this.handleTree(res.data.children, "categoryId");
      // 手动处理数据
      // this.categoryOptions = this.handleCategoryOption(res.data.children);
    },

    // 重置搜索表单
    resetQuery() {
      this.resetForm("goodsQueryRef");
      this.datetimeRange = [];
      this.queryCategoryIds = [];
      this.getList();
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },

    // 增，改，查商品信息
    handleGoods(action, row) {
      this.action = action;
      this.currentGoodInfo = cloneDeep(row);
      this.goodFormDialogVisiable = true;
    },

    // 选中行
    handleSelectChange(selection) {
      this.selectionList = selection;
    },

    // 批量删除
    async handleDelete() {
      const ids = this.selectionList.map((item) => item.commodityId);
      await pathDeleteCommodityApi(ids);
      this.deleteDialogVisible = false;
      this.msgSuccess("删除商品成功");
      this.getList();
    },

    // 上架
    handlePutway(row) {
      this.currentGoodInfo = cloneDeep(row);
      this.putwayDialog = true;
    },
  },
};
</script>
<style scoped lang="scss"></style>
